package jpa4azure.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaQuery;

import jpa4azure.type.TypeWrapper;
import jpa4azure.type.TypeWrapperFactory;

import com.windowsazure.samples.table.AzureTableEntity;
import com.windowsazure.samples.table.AzureTableEntityCollection;
import com.windowsazure.samples.table.AzureTableManager;
import com.windowsazure.samples.table.Filter;

public class FilterQuery<T> extends CriteriaQueryAdaptor<T> {

	Class<T> c;
	Filter filter;
	AzureTableManager client;
	
	public FilterQuery(Class<T> type, Filter f) {
		c = type;
		filter = f;
	}
	
	@Override
	public TypedQuery<T> getTypedQuery(final AzureEntityManager aem) {
		final TypeWrapper type = TypeWrapperFactory.wrap(c);
		this.client = aem.getTableStorageClient();

		return new TypedQueryAdaptor<T>() {
			
			@Override
			public List<T> getResultList() {
				List<T> list = new ArrayList<T>();
				AzureTableEntityCollection results = client.queryEntities(type.getTableName(), filter, null);
				for (AzureTableEntity e : results)
					list.add((T)aem.convert(e));
				return list;
			}
			
		};
	}
	
	public static <X> CriteriaQuery<X> from(Class<X> type, Filter f) {
		return new FilterQuery<X>(type, f);
	}

}
